package org.jsola.hr.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jsola.cache.ICache;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.CacheKeyKit;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IUserRegisterCensorDAO;
import org.jsola.hr.dto.UserRegisterCensorAddDTO;
import org.jsola.hr.dto.UserRegisterCensorAdminUpdateDTO;
import org.jsola.hr.dto.UserRegisterCensorUpdateDTO;
import org.jsola.hr.entity.UserRegisterCensorDO;
import org.jsola.hr.provider.IMessageProviderService;
import org.jsola.hr.query.UserRegisterCensorQuery;
import org.jsola.hr.service.IUserRegisterCensorService;
import org.jsola.hr.vo.UserRegisterCensorListVO;
import org.jsola.hr.vo.UserRegisterCensorVO;
import org.jsola.message.dto.ShortMessageDTO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.jsola.hr.constant.HrConstants.USER_REGISTER;

/**
 * 注册审核表
 *
 * @author zhr
 */
@Slf4j
@Service("hrUserRegisterCensorServiceImpl")
public class UserRegisterCensorServiceImpl implements IUserRegisterCensorService {

    /**
     * 代码生成的save() 方法需要siteId 和 userId 由于用户没有登录 无法获取siteId 和 userId 故设置该默认参数
     */
    private static final String SITE_ID = "default";

    private static final String USER_ID = "system" ;

    @Autowired
    private IUserRegisterCensorDAO userRegisterCensorDAO;

    @Autowired
    private IMessageProviderService messageProviderService;

    @Autowired
    private ICache cache;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public UserRegisterCensorVO save(UserRegisterCensorAddDTO userRegisterCensorAddDTO, TokenUser tokenUser) {
        // 转DO
        UserRegisterCensorDO userRegisterCensorDO = userRegisterCensorAddDTO.to(UserRegisterCensorDO.class);
        // 保存
        userRegisterCensorDO = save(userRegisterCensorDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return userRegisterCensorDO.to(UserRegisterCensorVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(UserRegisterCensorUpdateDTO userRegisterCensorUpdateDTO, TokenUser tokenUser) {
        //转DO
        UserRegisterCensorDO userRegisterCensorDO = userRegisterCensorUpdateDTO.to(UserRegisterCensorDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(userRegisterCensorDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... userRegisterCensorIds) {
        return deleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) userRegisterCensorIds);
    }


    @Override
    public UserRegisterCensorVO selectById(String userRegisterCensorId, String siteId) {
        UserRegisterCensorDO userRegisterCensorDO = selectDOById(userRegisterCensorId, siteId);
        if (userRegisterCensorDO == null) {
            return null;
        }
        return userRegisterCensorDO.to(UserRegisterCensorVO.class);
    }

    @Override
    public List<UserRegisterCensorListVO> select(UserRegisterCensorQuery userRegisterCensorQuery, String siteId) {
        List<UserRegisterCensorDO> userRegisterCensorDOList = selectDO(userRegisterCensorQuery, siteId);
        if(CollectionUtils.isEmpty(userRegisterCensorDOList)) {
            return userRegisterCensorDOList == null ? null : new ArrayList<>();
        }
        return userRegisterCensorDOList.stream()
                .map(userRegisterCensorDO -> userRegisterCensorDO.to(UserRegisterCensorListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(UserRegisterCensorQuery userRegisterCensorQuery, String siteId) {
        Example example = buildExample(userRegisterCensorQuery,siteId);
        return userRegisterCensorDAO.selectCountByExample(example);
    }

    @Override
    public Page<UserRegisterCensorListVO> selectPage(UserRegisterCensorQuery userRegisterCensorQuery, String siteId) {
        // 因为提交注册申请 没有siteId 所有使用默认的siteId
        Example example = buildExample(userRegisterCensorQuery,SITE_ID);
        Page<UserRegisterCensorDO> page = userRegisterCensorDAO.selectPageByExample(example,
                userRegisterCensorQuery.getPageNo(),
                userRegisterCensorQuery.getPageSize());

        return page.to(UserRegisterCensorListVO.class);
    }

    @Override
    public UserRegisterCensorDO selectDOById(String userRegisterCensorId, String siteId) {
        return listById(userRegisterCensorId, siteId);
    }

    @Override
    public List<UserRegisterCensorDO> selectDO(UserRegisterCensorQuery userRegisterCensorQuery, String siteId) {
        Example example = buildExample(userRegisterCensorQuery,siteId);
        return userRegisterCensorDAO.selectByExample(example);
    }

    @Override
    public int selectCountWithPhoneAndName(String phone, String name) {
        // 设置查询参数
        Example example = new Example(UserRegisterCensorDO.class);
        example.and()
                .andEqualTo("name", name)
                .andEqualTo("phone", phone);
        return userRegisterCensorDAO.selectCountByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int insertRegisterInfo(UserRegisterCensorAddDTO userRegisterCensorAddDTO) {
        // 转DO
        UserRegisterCensorDO userRegisterCensorDO = userRegisterCensorAddDTO.to(UserRegisterCensorDO.class);
        // 查询是否已存在
        int count = selectCountWithPhoneAndName(userRegisterCensorDO.getPhone()
                , userRegisterCensorDO.getName());
        if (count > 0) {
            throw new ParamException("请求重复！");
        }
        // 保存
        userRegisterCensorDO = save(userRegisterCensorDO, SITE_ID, USER_ID);
        sendMessage(userRegisterCensorDO.getName(),userRegisterCensorDO.getPhone());
        return 1;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int updateRegisterStatus(UserRegisterCensorAdminUpdateDTO userRegisterCensorAdminUpdateDTO, TokenUser tokenUser) {
        // 转DO
        UserRegisterCensorDO userRegisterCensorDO = userRegisterCensorAdminUpdateDTO.to(UserRegisterCensorDO.class);
        // 更新 采用默认的siteId
        return updateByIdSelective(userRegisterCensorDO, SITE_ID, tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void sendMessage(String name, String tel) {
        Map<String, Object> params = new HashMap<>(8);
        params.put("name", name);
        params.put("tel", tel);
        ShortMessageDTO shortMessageDTO = new ShortMessageDTO();
        shortMessageDTO.setScene(USER_REGISTER);
        // 写入短信内容
        shortMessageDTO.setParams(params);
        String registerSendKey = CacheKeyKit.getRegisterSend();
        List<String> sendPhoneList = cache.get(registerSendKey);
        if (!CollectionUtils.isEmpty(sendPhoneList)) {
            for (String phone : sendPhoneList) {
                shortMessageDTO.setPhone(phone);
                try {
                    messageProviderService.sendShortMessage(shortMessageDTO, null);
                } catch (Exception e) {
                    log.error(phone + "发送短信失败,失败信息{}", e.getMessage());
                }
            }
        }
    }

    /**
     * 根据查询参数，构建example
     * @param userRegisterCensorQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(UserRegisterCensorQuery userRegisterCensorQuery, String siteId) {
        Example example = new Example(UserRegisterCensorDO.class);
        example.and()
                .andEqualTo("siteId", siteId);
        if (userRegisterCensorQuery.getName() != null) {
            example.and().andLike("name", "%" + userRegisterCensorQuery.getName() + "%");
        }
        if (userRegisterCensorQuery.getCompanyName() != null) {
            example.and().andLike("companyName", "%" + userRegisterCensorQuery.getCompanyName() + "%");
        }
        if (userRegisterCensorQuery.getPhone() != null) {
            example.and().andLike("phone", "%" + userRegisterCensorQuery.getPhone() + "%");
        }
        if (userRegisterCensorQuery.getEmail() != null) {
            example.and().andLike("email", "%" + userRegisterCensorQuery.getEmail() + "%");
        }
        if (userRegisterCensorQuery.getRegisterReason() != null) {
            example.and().andEqualTo("registerReason", userRegisterCensorQuery.getRegisterReason());
        }
        if (userRegisterCensorQuery.getAuditStatus() != null) {
            example.and().andEqualTo("auditStatus", userRegisterCensorQuery.getAuditStatus());
        }
        // 排序
        ExampleKit.setExampleOrder(example,userRegisterCensorQuery.getOrders());
        return example;
    }
}




